<?php
/*
*管理文章
*/
namespace Admin\Controller;
use Think\Controller;
class PostsController extends AdminController {
	// 文章列表
    public function index(){
    	$posts = M('category')
    	->join('__POSTS__ on __CATEGORY__.category_slug = __POSTS__.category')
    	-> select();
    	$this -> assign('posts',$posts);
    	$this->display();
    }
    // 添加文章
    public function create(){
    	if(!IS_POST){
    		$this -> assign('category',M('category')->select());
    		$this -> display();
    	}else{
    		$data['title'] = I('title');
    		$data['content'] = I('content');
    		$data['category'] = I('category');
    		$data['created_at'] = time();
    		$data['updated_at'] = time();
    		if(I('status_code')=='on'){
    			$data['status'] = 'draft';
    		}else $data['status'] = 'public';

    		$post = M('posts')->add($data);
    		if($post>0) $this->success('发布成功','/admin/posts/index');
    		else $this -> error('发布失败');
    	}
    }
    // 修改文章
    public function edit($id){
    	if(!IS_POST){
	    	$this->assign('category',M('category')->select());
	    	$this->assign('post',M('posts') ->where('id=%d',$id)-> find());
	    	$this -> display();
    	}else{
    		$data['title'] = I('title');
    		$data['content'] = I('content');
    		$data['category'] = I('category');
    		$data['updated_at'] = time();
    		if(I('status_code')=='on'){
    			$data['status'] = 'draft';
    		}else $data['status'] = 'public';

    		$post =M('posts')->where('id=%d',$id)->save($data);
    		if($post>0){
                $this->success('修改成功','/admin/posts/index');
            }

    	}
    }
    // 删除文章
    public function delete($id){
    	if(IS_POST){
    		$post = M('posts')->where('id=%d',$id)->delete();
    		$this->success('删除成功');
    		// dd($GLOBALS);
    	}
    	else{
			$this->error('404 Not Found');

    	}
    }
}